import React, { Component, PropTypes } from 'react';
import { Utility, ApiInfo, RowItem } from 'components';
import { connect } from 'react-redux';
import * as CommonActions from 'redux/modules/reduxCommon';

const styles = require('./scss/ToGMessage.scss');

@connect(
  state => ({
    Title: state.Common.Title,                                             // 标题
    UrlParams: state.Common.UrlParams,                                     // URL参数
    DealtDetail: state.Common[Utility.constItem.StateName.DealtDetail],    // 
    CommonData: state.Common,                                              // 
    DealtDetailTemp: state.Common.DealtDetailTemp,                                              // 
  }),
  { ...CommonActions })

export default class ToGMessage extends Component {
  static propTypes = {
    Title: PropTypes.string,                                            // 标题
    UrlParams: PropTypes.object,                                        // url 参数
    DealtDetail: PropTypes.object,                                      //
    DealtDetailTemp: PropTypes.object,                                  //
    CommonData: PropTypes.object,                                       //
    onDeleteByFields: PropTypes.func,                                   // 
    onSetContent: PropTypes.func,                                       // 
    onUpdateRedux: PropTypes.func,                                      // 
    onApiGet: PropTypes.func,                                           // 
    onApiPost: PropTypes.func,                                          // 
    onUpdateObjectCopy: PropTypes.func,                                          // 
  };

  constructor(props) {
    super(props);
    this.state = {};

    const { ExecutePlanType, RemindType, RepeatWay, WorkWay } = Utility.constItem.StateInfo;
    const MessageInfo = {
      Desc: '这里是要显示的内容',
      PlanType: ExecutePlanType[0],
      EndDate: new Date().getTime(),
      RemindType: RemindType[0],
      Labels: [],
      RepeatType: RepeatWay[0],
      WorkType: WorkWay[0],
      PeopleList: []
    };

    const a = Utility.$convertToDateByTimestamp(new Date().getTime(), 'yyyy-MM-dd') + ' 18:00';
    MessageInfo.EndDate = Utility.$convertToTimestamp(a);
    this.state.MessageInfo = MessageInfo;
  }

  componentWillMount() {
    this.__InitDataByRedux();
  }

  componentDidMount() {
    this.state.IsMount = true;
    this.__InitData();
  }

  componentWillUnmount() {
    delete this.state.IsMount;
  }

  __InitData() {
    const { UrlParams, onApiGet, DealtDetail } = this.props;
    if (!Utility.isFunction(onApiGet)) {
      return;
    }
    const { id } = UrlParams;
    if (!id) {
      return;
    }
    if (DealtDetail && DealtDetail.id === parseInt(id, 0)) {
      this.__InitRef();
      return;
    }
    Utility.$loading();
    onApiGet(Utility.constItem.StateName.DealtDetail,
      Utility.format(ApiInfo.JXDB.Detail, id), {}).then(() => {
        this.__InitRef();
        this.__UpdateRender();
        Utility.$loadingHide();
      }, () => {
        Utility.$loadingHide();
      });
  }

  __InitDataByRedux() {
    const { CommonData } = this.props;
    if (!CommonData) {
      return;
    }
    const { MessageInfo } = this.state;
    const { SelectEndDate, SelectExecutePlanType, SelectLabelType, SelectRemindType, SelectRepeatWay, SelectWorkWay } = Utility.constItem.StateName;
    // 计划类型
    if (CommonData[SelectExecutePlanType]) {
      MessageInfo.PlanType = CommonData[SelectExecutePlanType];
    }
    // 标签
    if (CommonData[SelectLabelType]) {
      const lTypes = CommonData[SelectLabelType];
      const Labels = Object.values(lTypes).sort((a, b) => Number(a.Id) - Number(b.Id));
      MessageInfo.Labels = Labels;
    }
    // 提醒
    if (CommonData[SelectRemindType]) {
      MessageInfo.RemindType = CommonData[SelectRemindType];
    }
    // 工作方式
    if (CommonData[SelectWorkWay]) {
      MessageInfo.WorkType = CommonData[SelectWorkWay];
    }
    // 重复方式
    if (CommonData[SelectRepeatWay]) {
      MessageInfo.RepeatType = CommonData[SelectRepeatWay];
    }
    // 时间
    if (CommonData[SelectEndDate] && CommonData[SelectEndDate] > 1000000) {
      MessageInfo.EndDate = CommonData[SelectEndDate];
    }

    this.__UpdateRender();
  }

  __InitRef() {
    const { DealtDetail, onSetContent, DealtDetailTemp } = this.props;
    const { content } = DealtDetailTemp || DealtDetail || {};
    if (!DealtDetailTemp) {
      onSetContent('DealtDetailTemp', JSON.parse(JSON.stringify(DealtDetail)));
    }
    const { txtDesc } = this.refs;
    if (!txtDesc) {
      return;
    }
    txtDesc.value = content;
  }

  /**
   * 更新渲染
   */
  __UpdateRender() {
    if (!!this.state.IsMount) {
      this.setState({ __CurrentTempDate: new Date().getTime() });
    }
  }

  __HandlerBlur(event) {
    const { DealtDetailTemp } = this.props;
    if (DealtDetailTemp) {
      DealtDetailTemp.content = event.target.value;
    }
  }

  __HandlerSubmit() {
    const { onDeleteByFields, onApiPost, DealtDetailTemp, onSetContent } = this.props;
    const { SelectEndDate, SelectExecutePlanType, SelectLabelType, SelectRemindType, SelectRepeatWay, SelectWorkWay } = Utility.constItem.StateName;
    const __Clear = () => {
      onSetContent('DealtDetailTemp', null);
      onSetContent(SelectExecutePlanType, null);
      onSetContent(SelectLabelType, null);
      onSetContent(SelectRemindType, null);
      onSetContent(SelectRepeatWay, null);
      onSetContent(SelectWorkWay, null);
      onSetContent(SelectEndDate, null);
      onSetContent(Utility.constItem.StateName.DealtDetail, null);
    };

    const { MessageInfo } = this.state;
    const { PlanType, EndDate, RemindType, Labels, RepeatType, WorkType } = MessageInfo;
    const data1 = {
      execPlan: PlanType.Value,
      isRemind: RemindType.Value,
      deadline: Utility.$convertToDateByTimestamp(EndDate, 'yyyy-MM-dd HH:mm:ss'),
      isRepeat: RepeatType.Value,
      workMode: WorkType.Value,
      label: Labels.map((item) => item.Title).join(',')
    };
    data1.content = this.refs.txtDesc.value;

    const data = Object.assign({}, DealtDetailTemp, data1);
    console.log(data);
    if (data.execPlan !== 'LIGTH') {
      if (EndDate < new Date().getTime()) {
        Utility.$alert('截止时间不能小于当前时间');
        return;
      }
    }

    const __submit = () => {
      Utility.$loading();
      onApiPost('ToGMessageSaveInfo', ApiInfo.JXDB.Add, { data }).then(() => {
        onDeleteByFields('GxMessageDealt', { Key: 'id', Value: data.id });
        __Clear();
        Utility.$goBack();
      }, () => {
        Utility.$loadingHide();
      });
    };

    Utility.$actionSheetBtns([{
      Title: '提交', onClick: () => {
        Utility.$actionSheetHide();
        setTimeout(() => {
          __submit();
        }, 200);
      }
    }]);
  }

  __HandlerOpenDatePicker(currentDate) {
    const __self = this;
    const { onSetContent } = this.props;
    Utility.$openDatePicker(currentDate ? new Date(currentDate) : new Date(), true, (value) => {
      onSetContent(Utility.constItem.StateName.SelectEndDate, value.getTime());
      __self.state.MessageInfo.EndDate = value.getTime();
      __self.__UpdateRender();
    });
  }

  __BuildLabesHtml(Labels) {
    if (!Utility.isArray(Labels)) {
      return '无';
    }
    return (<div className={styles.label}>
      {
        Labels.map((row, index) => {
          return (<div key={index} className={styles.lab + ' ' + (styles['bgStyle_' + row.BgStyle])}>{row.Title}</div>);
        })
      }
    </div>);
  }

  __HandlerSelectPeople() {
    // const { MessageInfo } = this.state;
    // const { PeopleList } = MessageInfo;
    // let pIdList = [];
    // if (Utility.isArray(PeopleList)) {
    //   pIdList = PeopleList.map((item) => item.userId);
    // }
    // const self = this;
    // Utility.$platformApi.$selectUser(pIdList, true, (data) => {
    //   const { users } = data || {};
    //   MessageInfo.PeopleList = users;
    //   Utility.$alert(JSON.stringify(MessageInfo.PeopleList));
    //   self.__UpdateRender();
    // }, (err) => {
    //   Utility.$alert(JSON.stringify(err));
    // });
  }

  __HandlerTaskStatus(status) {
    console.log(status);
  }

  __GetPeopleInfo() {
    // PeopleList.map((a) => a.username).join(',')
    const { DealtDetail } = this.props;
    const { extTaskTodoUsers, extTaskUser } = DealtDetail || {};
    const _extTaskTodoUsers = extTaskTodoUsers || extTaskUser;
    if (!Utility.isArray(_extTaskTodoUsers)) {
      return '';
    }

    if (_extTaskTodoUsers.length > 3) {
      return _extTaskTodoUsers.slice(0, 3).map(item => item.taskUserName).join(',') + '等' + _extTaskTodoUsers.lenth + '人';
    }
    return _extTaskTodoUsers.slice(0, 3).map(item => item.taskUserName).join(',');
  }

  render() {
    const { Desc, EndDate, PlanType, RemindType, Labels, RepeatType, WorkType } = this.state.MessageInfo;
    const { Id } = PlanType;
    const { SelectLabel, SelectRemind, SelectExecutePlan, SelectRepeatWay, SelectWorkWay } = Utility.constItem.UrlItem;
    return (
      <div className={styles.togMessageCss}>
        <textarea className={styles.desc} maxLength="500" ref="txtDesc"
          defaultValue={Desc} onBlur={this.__HandlerBlur.bind(this)}></textarea>
        <RowItem LeftTitle="执行计划" RightTitle={PlanType.Title} HideTopLine HideBottomLine onSelect={() => Utility.toPage(SelectExecutePlan)} />
        <div className={styles.splitLine}></div>

        {
          Id > 1 && <div>
            <RowItem LeftTitle="提醒" RightTitle={RemindType.Title} HideTopLine onSelect={() => Utility.toPage(SelectRemind)} />
            <RowItem LeftTitle="截止时间" RightTitle={Utility.$convertToDateByTimestamp(EndDate, 'yyyy-MM-dd HH:mm:ss')} HideTopLine onSelect={this.__HandlerOpenDatePicker.bind(this, EndDate)} />
            <RowItem LeftTitle="标签" RightData={this.__BuildLabesHtml(Labels)} HideTopLine onSelect={() => Utility.toPage(SelectLabel)} />
            <RowItem LeftTitle="重复" RightTitle={RepeatType.Title} HideTopLine onSelect={() => Utility.toPage(SelectRepeatWay)} />
            <RowItem LeftTitle="工作方式" RightTitle={WorkType.Title} HideTopLine
              HideBottomLine={Id === 2 ? true : false} onSelect={() => Utility.toPage(SelectWorkWay)} />

            {
              Id === 2 && <div className={styles.splitLine}></div>
            }

          </div>
        }
        {
          Id === 3 && <div>
            <RowItem LeftTitle="相关任务" RightTitle="进入相关任务列表" HideTopLine />
            <RowItem LeftTitle="结果通知" RightTitle="哈哈" HideTopLine HideBottomLine />
            <div className={styles.splitLine}></div>
          </div>
        }

        <RowItem LeftTitle={Id === 1 ? '参与人' : '接收人'} RightTitle={this.__GetPeopleInfo()} HideTopLine HideBottomLine onSelect={this.__HandlerSelectPeople.bind(this)} />

        <div className={styles.btns}>
          <div className={styles.btn} onClick={this.__HandlerSubmit.bind(this)}>提交</div>
          {
            Id === -100 &&
            <div>
              <div className={styles.btn} onClick={this.__HandlerTaskStatus.bind(this, 1)}>关闭任务</div>
              <div className={styles.btn} onClick={this.__HandlerTaskStatus.bind(this, 2)}>删除任务</div>
              <div className={styles.btn} onClick={this.__HandlerTaskStatus.bind(this, 3)}>复制任务</div>
            </div>
          }
        </div>
      </div>
    );
  }
}

